<?php

/**
 * IndexController - The default controller class
 * 
 * @author
 * @version 
 */

require_once 'Zend/Controller/Action.php';

class Administrator_SystemController extends Zend_Controller_Action 
{
	

	public function init(){
		
		$member=new CMember();
		
		if(!$member->isUser($this->_request->getModuleName(),$this->_request->getControllerName())){	
			
			$this->_redirect(MY_URL.'/administrator-auth-login');
			
		}
		
		$memberArray = $member->getUserDetails(array('uid' => $_COOKIE[COOKIE_PRE.'uid']));
    	if($_COOKIE[COOKIE_PRE.'uid']=='1'){
				
		} else {
        	$strarray = explode(",", $memberArray[0]['menuflag']);
        	
        	if (!in_array('11', $strarray)) {
        		exit('no priviage');
        	}
		}
		
	}
	
	public function preDispatch()
	{
		
		$this->getHelper ('layout')->setLayout('framelayout');
		
		$this->view->addHelperPath(MY_ROOT.'/vhelpers');
		
		Zend_Controller_Action_HelperBroker::addPath(MY_ROOT.'/chelpers');
		
		//$this->getHelper('User')->getinfo($this->view,$this->_request->getModuleName(),$this->_request->getControllerName());
		
	}
	

	
	
	public function docacheAction(){
		
		$this->_helper->viewRenderer->setNoRender();
		
		Zend_Registry::get('myCache')->clean(Zend_Cache::CLEANING_MODE_ALL);
		
		$this->view->showMsg("更新缓存成功!");
		
	}
	
	public function configAction(){
		
		$config=new CConfig();
		
		$array=$config->getAllConfigs();
		
		$configArray=array();
		
		foreach ($array as $value){

			$configArray[$value['name']]=$value['data'];
			
		}
		
		$this->view->assign('configArray',$configArray);
		
	}
	
	public function moreconfigAction(){
		
		$config=new CConfiguration();
		
		$array=$config->getAllConfigurations();
		
		$configArray=array();
		
		foreach ($array as $value){

			$configArray[$value['name']]=$value['data'];
			
		}
		
		$this->view->assign('configArray',$configArray);
		
		require_once (MY_ROOT."/fckeditor/fckeditor.php");
		
		$oFCKeditor = new FCKeditor('REGISTER_EMAIL_BODY') ;
		
		$oFCKeditor->BasePath	= ROOT_PATH.'/fckeditor/' ;
		
		$oFCKeditor->Value		= $configArray['REGISTER_EMAIL_BODY'];
		
		$oFCKeditor->Height=400;
		
		$oFCKeditor->Width="98%";
		
		$this->view->assign('oFCKeditor',$oFCKeditor);
		
	}
	
	public function admailAction()
	{
		$config=new CConfiguration();
		
		$array=$config->getAllConfigurations();
		
		$configArray=array();
		
		foreach ($array as $value){

			$configArray[$value['name']]=$value['data'];
			
		}
		
		$this->view->assign('configArray',$configArray);
		
		require_once (MY_ROOT."/fckeditor/fckeditor.php");
		
		$oFCKeditor = new FCKeditor('AD_EMAIL_BODY') ;
		
		$oFCKeditor->BasePath	= ROOT_PATH.'/fckeditor/' ;
		
		$oFCKeditor->Value		= $configArray['AD_EMAIL_BODY'];
		
		$oFCKeditor->Height=400;
		
		$oFCKeditor->Width="98%";
		
		$this->view->assign('oFCKeditor',$oFCKeditor);
	}
	
	public function dosendmailAction()
	{
		$time1 = $this->getRequest()->getParam('time1');
		$time2 = $this->getRequest()->getParam('time2');
		$adMailSubject = $this->getRequest()->getParam('AD_EMAIL_SUBJECT');
		$adMailBody = $this->getRequest()->getParam('AD_EMAIL_BODY');
		
		$config = new CConfiguration();
		
		if (!$config->getDetail('AD_EMAIL_SUBJECT')) {
			$config->insert(array('name'=>'AD_EMAIL_SUBJECT', 'data'=>''));
		}
		
		if (!$config->getDetail('AD_EMAIL_BODY')) {
			$config->insert(array('name'=>'AD_EMAIL_BODY', 'data'=>''));
		}
		
		$config->editConfiguration('AD_EMAIL_SUBJECT',array('data'=>$adMailSubject));
		$config->editConfiguration('AD_EMAIL_BODY',array('data'=>$adMailBody));

		$member = new CMember();
		$db = $member->getAdapter();
		$select = $db->select();
		$select->from('zcshop_members', '*');
		if (!empty($time1)) {
			$select->where('reg_time > ?', strtotime($time1));
		}
		
		if (!empty($time2)) {
			$select->where('reg_time < ?', strtotime($time2));
		}

		$result = $db->fetchAll($select);
		$emailArr = array();
		$uidArr = array();
		
		
		foreach ($result as $v) {
			$emailArr[] = $v['email'];
			$uidArr[] = $v['uid'];
		}
		if (!empty($emailArr)) {
			$select = $db->select();
			$select->from('zcshop_order_contacts', '*')
				   ->where('uid in (' . implode(',', $uidArr) . ')');
			$result = $db->fetchAll($select);
			
			foreach ($result as $v) {
				$emailArr[] = $v['email'];
			}
		}
		
		$emailArr = array_unique($emailArr);	
		$mail = new CMail();	
		
		$from = $config->getDetail('EMAIL_NAME');
		$from = 'service@newjerseysoccer.net';		
		echo '开始发送邮件。</br>';
		
		foreach ($emailArr as $v) {
			if (!empty($v)) {
				$mail->sendEmail($from, $v, $adMailSubject, $adMailBody);
				echo $v . '已发送。</br>';
			}
		}
		
		echo '发送完成。</br>';
	}
	
	public function previewAction()
	{
		$time1 = $this->getRequest()->getParam('time5');
		$time2 = $this->getRequest()->getParam('time6');
		$adMailSubject = $this->getRequest()->getParam('subject');
		$adMailBody = $this->getRequest()->getParam('content');	
		
		$member = new CMember();
		$db = $member->getAdapter();
		$select = $db->select();
		$select->from('zcshop_members', '*');
		if (!empty($time1)) {
			$select->where('reg_time > ?', strtotime($time1));
		}
		
		if (!empty($time2)) {
			$select->where('reg_time < ?', strtotime($time2));
		}

		$result = $db->fetchAll($select);
		$emailArr = array();
		$uidArr = array();
		
		
		foreach ($result as $v) {
			$emailArr[] = $v['email'];
			$uidArr[] = $v['uid'];
		}
		if (!empty($emailArr)) {
			$select = $db->select();
			$select->from('zcshop_order_contacts', '*')
				   ->where('uid in (' . implode(',', $uidArr) . ')');
			$result = $db->fetchAll($select);
			
			foreach ($result as $v) {
				$emailArr[] = $v['email'];
			}
		}
		
		$emailArr = array_unique($emailArr);
		
		$this->view->subject = $adMailSubject;
		$this->view->content = $adMailBody;
		$this->view->email = $emailArr;
	}
	
	public function domoreconfigAction(){
		
		$this->_helper->viewRenderer->setNoRender();
		
		$configArray=$this->_request->getParams();
		
		$config=new CConfiguration();
		
		foreach ($configArray as $key => $value){
			
			$config->editConfiguration($key,array('data'=>$value));
			
		}
		
		$this->view->showMsg('更新成功!');
		
	}

	public function configorderemailAction(){

		$config=new CConfigorderemail();

		$array=$config->getAllConfigorderemail();

		$configArray=array();

		foreach ($array as $value){

			$configArray[$value['name']]=$value['data'];

		}

		$this->view->assign('configArray',$configArray);

		require_once (MY_ROOT."/fckeditor/fckeditor.php");

		$oFCKeditor = new FCKeditor('REGISTER_EMAIL_BODY') ;

		$oFCKeditor->BasePath	= ROOT_PATH.'/fckeditor/' ;

		$oFCKeditor->Value		= $configArray['REGISTER_EMAIL_BODY'];

		$oFCKeditor->Height=400;

		$oFCKeditor->Width="98%";

		$this->view->assign('oFCKeditor',$oFCKeditor);

	}

	public function doconfigorderemailAction(){

		$this->_helper->viewRenderer->setNoRender();

		$configArray=$this->_request->getParams();

		$config=new CConfigorderemail();

		foreach ($configArray as $key => $value){

			$config->editConfigorderemail($key,array('data'=>$value));

		}

		$this->view->showMsg('更新成功!');

	}
	
	public function configpayemailAction(){

		$config=new CConfigpayemail();

		$array=$config->getAllConfigpayemail();

		$configArray=array();

		foreach ($array as $value){

			$configArray[$value['name']]=$value['data'];

		}

		$this->view->assign('configArray',$configArray);

		require_once (MY_ROOT."/fckeditor/fckeditor.php");

		$oFCKeditor = new FCKeditor('REGISTER_EMAIL_BODY') ;

		$oFCKeditor->BasePath	= ROOT_PATH.'/fckeditor/' ;

		$oFCKeditor->Value		= $configArray['REGISTER_EMAIL_BODY'];

		$oFCKeditor->Height=400;

		$oFCKeditor->Width="98%";

		$this->view->assign('oFCKeditor',$oFCKeditor);

	}

	public function doconfigpayemailAction(){

		$this->_helper->viewRenderer->setNoRender();

		$configArray=$this->_request->getParams();

		$config=new CConfigpayemail();

		foreach ($configArray as $key => $value){

			$config->editConfigpayemail($key,array('data'=>$value));

		}

		$this->view->showMsg('更新成功!');

	}

	public function doconfigAction(){
		
		$this->_helper->viewRenderer->setNoRender();
		
		$configArray=$this->_request->getParams();
		
		$config=new CConfig();
		
		foreach ($configArray as $key => $value){
			
			$config->editConfig($key,array('data'=>$value));
			
		}
		
		$this->view->showMsg('更新成功!');
		
	}
	

	public function navAction(){
		
		$navContent=file_get_contents(MY_ROOT.'/html/upload/nav/nav.txt');
		
		$navArray=array();
		
		if($navContent!=''){
			
			$navArray=json_decode($navContent,true);
			
		}
		
		$this->view->assign('navArray',$navArray);
		
	}
	
	public function cateconfigAction(){
		
		$cateString=file_get_contents(MY_ROOT.'/html/upload/category/category.txt');
		
		$cateArray=array();
		
		if($cateString!=''){
			
			$cateArray=json_decode($cateString,true);
			
		}
		
		$this->view->assign('cateArray',$cateArray);
		
	}
	
	public function docateconfigAction(){
		
		$this->_helper->viewRenderer->setNoRender();
		
		$cateConfigArray=$this->_request->getParams();
		
		$cateArray=array();

		foreach ($cateConfigArray as $key => $value){

			if(strpos($key,'_cate')){
	
				$cateArray[$key]=$value;
				
			}
			
		}
		
		$cateString=json_encode($cateArray);
		
		file_put_contents(MY_ROOT.'/html/upload/category/category.txt',$cateString);
		
		$this->view->showMsg('更新成功!');
		
	}
	
	public function donavAction(){
		
		$this->_helper->viewRenderer->setNoRender();
		
		$navName=$this->_request->getParam('navName');
		
		$navUrl=$this->_request->getParam('navUrl');
		
		$navOrder=$this->_request->getParam('navOrder');
		
		$navArray=array();
		
		for($i=0;$i<count($navName);$i++){
			
			if($navName[$i]!=''){
			
				$navArray[$i]['name']=trim($navName[$i]);
				
				$navArray[$i]['url']=trim($navUrl[$i]);
				
				$navArray[$i]['order']=trim($navOrder[$i]);
			
			}
			
		}
		
		$navString=json_encode($navArray);
		
		file_put_contents(MY_ROOT.'/html/upload/nav/nav.txt',$navString);
		
		$this->view->showMsg('更新成功!');
		
	}
	
	public function postAction(){
	
		//$this->_helper->viewRenderer->setNoRender();
		
		//$this->getHelper ('layout')->disableLayout ();
	
	}
    
	public function createindexAction()
	{
		set_time_limit(0);
		$this->_helper->viewRenderer->setNoRender();
		
		$index=Zend_Search_Lucene::create(MY_ROOT."/indexdata/index");
		$analyzer = new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive(); 
//		$stopWords = array('a', 'an', 'at', 'the', 'and', 'or', 'is', 'am'); 
//        $stopWordsFilter = new Zend_Search_Lucene_Analysis_TokenFilter_StopWords($stopWords);
//        $analyzer->addFilter($stopWordsFilter); 
		Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
		
		
		
		
		$item=new CItem();
		$result = $item->getAllItems(0,0,'product',0,0,'has_banned',$where='zcshop_products.is_showed=1 and zcshop_products.onsales=0');
		$success = 0;
		
		for($i=0;$i<count($result);$i++){//count($result)
			try{
			$doc=new Zend_Search_Lucene_Document();
			$doc->addField(Zend_Search_Lucene_Field::UnIndexed('PID',$result[$i]['itemid']));
			$doc->addField(Zend_Search_Lucene_Field::UnStored('subject',$result[$i]['subject']));
			$doc->addField(Zend_Search_Lucene_Field::UnIndexed('px',$result[$i]['px']));
			$doc->addField(Zend_Search_Lucene_Field::UnStored('content',$result[$i]['pattern_intro'] . ' ' . $this->view->toText($result[$i]['content']) . ' ' . $result[$i]['keywords'] . ' ' . $result[$i]['description'],'utf-8'));
			$index->addDocument($doc);
			}catch (Exception $e)
			{
				echo $e->getMessage();exit;
			}
			$success++;
		}
		$index->optimize();
		$index->commit();
		$this->view->showMsg('成功生成索引,共为'.$success.'个产品生成索引!','administrator-system-search');
		return false;
	}
    
	public function searchAction()
	{
		$myCache=Zend_Registry::get('myCache');
		$myQuery=$this->_request->getParam('query');
		$cacheId=md5($myQuery);
		if(trim($myQuery)==""){
			return false;
		}
		$result=$myCache->load($cacheId);
		if(!$result){
			$index=Zend_Search_Lucene::open(MY_ROOT."/indexdata/index");
			Zend_Search_Lucene_Search_QueryParser::setDefaultOperator(Zend_Search_Lucene_Search_QueryParser::B_AND);
			$query=Zend_Search_Lucene_Search_QueryParser::parse($myQuery,'utf-8');
			$hits=$index->find($query);
			$myHits=array();
			foreach($hits as $hit){
				$newHits=new stdClass();
				$newHits->PID=$hit->PID;
				$myHits[]=$newHits;
				unset($newHits);
			}
			$myCache->save($myHits,$cacheId);
		}else{
			$hits=$result;
		}
		$PIDS = array();
		foreach ($hits as $hit)
		{
			$PIDS[] = $hit->PID;
		}
		var_dump($PIDS);exit;
	}
    
	public function hotsearchAction()
	{}
    
	public function doaddhotsearchAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		$thisArray=$this->_request->getParams();
		$filters = array(
    		'*'   => 'StringTrim'
		);
		$validators = array();
		$input = new Zend_Filter_Input($filters, $validators, $thisArray);
		/*插入到条目表 start*/
		$hs=new CHotSearch();
		$addData=array(
			'keyword'=>$input->keyword,
			'order'=>$input->order,
			'time'=>time(),
		);
		$hs->createHotSearch($addData);

		$this->view->showMsg('添加成功!','administrator-system-hotsearchlist');
	}
    
	public function edithotsearchAction()
	{
		$id=$this->_request->getParam('id');
    	$hs=new CHotSearch();
    	$itemArray=$hs->getDetail($id);
    	$this->view->assign('itemArray',$itemArray);
	}
    
	public function doedithotsearchAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		$thisArray=$this->_request->getParams();
		$filters = array(
    		'*'   => 'StringTrim'
		);
		$validators = array();
		$input = new Zend_Filter_Input($filters, $validators, $thisArray);
		/*插入到条目表 start*/
		$hs=new CHotSearch();
		$addData=array(
			'keyword'=>$input->keyword,
			'order'=>$input->order,
			'time'=>time(),
		);
		$hs->editHotSearch($input->id,$addData);

		$this->view->showMsg('更新成功!');
	}
    
	public function hotsearchlistAction()
	{
		$page=$this->_request->getParam('page');
    	
		$hs = new CHotSearch();
		
		$itemCounts=$hs->getAllItemCounts('');
		
    	Zend_Loader::loadClass("CFilter");
    	
    	$pageArray = CFilter::filterPage ( $page, $itemCounts, 5 );
		$itemArray=$hs->hslist($pageArray['from'],5);
		
		Zend_Loader::loadClass("CPage");
    	
    	$pageString = CPage::divPages( $pageArray ['pageNumber'], $pageArray ['page'], ROOT_PATH."/administrator-system-hotsearchlist?"); //生成分页字符串
    	
    	$this->view->assign ( "pageString", $pageString );
    	
    	$this->view->assign ( "pageArray", $pageArray );
		
		$this->view->assign('itemArray',$itemArray);
	}
    
	public function delhotsearchAction()
	{
		$this->_helper->viewRenderer->setNoRender();
    	$id = $this->_request->getParam('id');
    	$hs = new CHotSearch();    	
    	$hs->hsdelete($id);    	
    	$this->view->showMsg('删除成功!');
	}
	
	public function attrAction()
	{
		if ($this->getRequest()->isPost()) {
			
			$attrModel = new CAttr();
			$categoryName = $this->getRequest()->getParam('category_name', '');
			$categoryOrder = $this->getRequest()->getParam('category_order', '');
			$categoryId = $this->getRequest()->getParam('category_id', '');
			$categoryDesc = $this->getRequest()->getParam('category_desc', '');
			
			for ($i = 0; $i < count($categoryName); $i++) {
				if (!empty($categoryName[$i])) {
					$attrModel->updateAttr($categoryName[$i], intval($categoryOrder[$i]), $categoryId[$i], $categoryDesc[$i], 1);
				}				
			}
			
			$brandName = $this->getRequest()->getParam('brand_name', '');
			$brandOrder = $this->getRequest()->getParam('brand_order', '');
			$brandId = $this->getRequest()->getParam('brand_id', '');
			$brandDesc = $this->getRequest()->getParam('brand_desc', '');
			
			for ($i = 0; $i < count($brandName); $i++) {
				if (!empty($brandName[$i])) {
					$attrModel->updateAttr($brandName[$i], intval($brandOrder[$i]), $brandId[$i],$brandDesc[$i], 2);	
				}			
			}
			
			$playerName = $this->getRequest()->getParam('player_name', '');
			$playerOrder = $this->getRequest()->getParam('player_order', '');
			$playerId = $this->getRequest()->getParam('player_id', '');
			$playerDesc = $this->getRequest()->getParam('player_desc', '');
			
			for ($i = 0; $i < count($playerName); $i++) {
				if (!empty($playerName[$i])) {
					$attrModel->updateAttr($playerName[$i], intval($playerOrder[$i]), $playerId[$i], $playerDesc[$i], 3);		
				}		
			}
			
			$this->getHelper('viewRenderer')->setNoRender();
			$this->_redirect('administrator-system-attr');			
		} else {
			$attrModel = new CAttr();
			$category = $attrModel->getByType(1);
			$brand = $attrModel->getByType(2);
			$player = $attrModel->getByType(3);
			$this->view->category = $category;
			$this->view->brand = $brand;
			$this->view->player = $player;
		}		
		
	}
	
	public function delattrAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$id = $this->getRequest()->getParam('id', 0);
		$id = intval($id);
		if ($id >0) {
			$attr = new CAttr();
			try {
				$flag = $attr->del($id);
			} catch (Exception $e) {
				print_r($e);
			}
			if ($flag == 0) {
				echo 0;exit();
			} elseif ($flag == 1) {
				echo 1;exit();
			} else {
				echo 3;exit();
			}
		}
	}
	public function linkAction(){
		$linksModel = new Clinks();
		$category = $linksModel->show(0);
		$this->view->category = $category;

	}
    public function addlinksAction(){
        $this->getHelper('viewRenderer')->setNoRender();
        //$this->getHelper('layout')->disableLayout();
        $linksModel = new Clinks();
        $pid = $this->getRequest()->getParam('pid', 1);
		$data['pid'] = intval($pid);
        $name = $this->getRequest()->getParam('linkname');
		$data['name'] = trim($name);
        $url = $this->getRequest()->getParam('linkurl');
		$data['url'] = trim($url);
        $description = $this->getRequest()->getParam('description');
        $data['description'] = trim($description);
		$id = $linksModel->create($data);
        if($id!=false){
			//$this->getHelper('viewRenderer')->setNoRender();
			//$this->_redirect('administrator-system-link');		
            $this->view->showMsg('添加成功!','administrator-system-link');	
        }else{
			$this->view->showMsg('添加失败!','administrator-system-link');	
		}
       
        
    }
    
}
